import React, { Component } from "react";
import { Table, Input, Button, Space, Divider, Popconfirm } from "antd";
import Highlighter from "react-highlight-words";
import { SearchOutlined } from "@ant-design/icons";
import { Inquirylist, DeleteInquiry } from "../../../services/auth";

export default class Inquiry_list extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchText: "",
      searchedColumn: "",
      arr: [],
      dataSource: [],
    };
  }

  componentWillMount() {
    Inquirylist().then(
      (response) => {
        console.log(response.data); ////查看
        //拿到我们想要渲染的数据(res)
        this.state.arr = response.data; //更新state，让视图刷新
        this.setState({
          dataSource: this.state.arr,
        });
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }

  handleDelete = (id) => {
    const dataSource = [...this.state.dataSource];
    this.setState({
      dataSource: dataSource.filter((item) => item.id !== id),
    });
    ///////发送delete请求，待测试
    DeleteInquiry(id).then(
      (response) => {
        console.log(response.data);
      },
      (error) => {
        console.log("删除失败", error);
      }
    );
  };

  getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={(node) => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() =>
            this.handleSearch(selectedKeys, confirm, dataIndex)
          }
          style={{ marginBottom: 8, display: "block" }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => this.handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => {
              confirm({ closeDropdown: false });
              this.setState({
                searchText: selectedKeys[0],
                searchedColumn: dataIndex,
              });
            }}
          >
            Filter
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered) => (
      <SearchOutlined style={{ color: filtered ? "#1890ff" : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase())
        : "",
    onFilterDropdownVisibleChange: (visible) => {
      if (visible) {
        setTimeout(() => this.searchInput.select(), 100);
      }
    },
    render: (text) =>
      this.state.searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
          searchWords={[this.state.searchText]}
          autoEscape
          textToHighlight={text ? text.toString() : ""}
        />
      ) : (
        text
      ),
  });

  handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    this.setState({
      searchText: selectedKeys[0],
      searchedColumn: dataIndex,
    });
  };

  handleReset = (clearFilters) => {
    clearFilters();
    this.setState({ searchText: "" });
  };

  render() {
    const { handleClick, user_id } = this.props;

    const columns = [
      {
        title: "询价单编号",
        dataIndex: "id",
        key: "id",
        align: "center",
        ...this.getColumnSearchProps("id"),
      },
      {
        title: "公司名称",
        dataIndex: "company_name",
        key: "company_name",
        align: "center",
        ...this.getColumnSearchProps("company_name"),
      },
      {
        title: "询价日期",
        dataIndex: "valid_from",
        key: "valid_from",
        align: "center",
        ...this.getColumnSearchProps("valid_from"),
      },
      {
        title: "询价有效期至",
        dataIndex: "valid_to",
        key: "valid_to",
        align: "center",
        ...this.getColumnSearchProps("valid_to"),
      },
      {
        title: "操作员",
        dataIndex: "operator_id",
        key: "operator_id",
        align: "center",
        ...this.getColumnSearchProps("operator_id"),
        sorter: (a, b) => a.operator_id - b.operator_id,
      },
      {
        title: "状态",
        dataIndex: "status",
        key: "status",
        align: "center",
        ...this.getColumnSearchProps("status"),
      },
      {
        title: "",
        key: "action",
        align: "center",
        render: (_, record) => (
          <Space>
            <Button
              size="small"
              onClick={() => {
                handleClick(false, record);
              }}
            >
              详情
            </Button>

            <Divider type="vertical" />
            {record.operator_id === user_id ? (
              <Button
                onClick={() => {
                  handleClick(true, record);
                }}
                type="primary"
                size="small"
              >
                编辑
              </Button>
            ) : (
              <Button type="primary" size="small" disabled>
                编辑
              </Button>
            )}
            <Divider type="vertical" />
            {record.operator_id === user_id && record.status === "已处理" ? ( //已处理且为自己的才能删除
              <Popconfirm
                title="确定要删除吗？"
                onConfirm={() => this.handleDelete(record.id)}
              >
                <Button type="danger" size="small">
                  删除
                </Button>
              </Popconfirm>
            ) : (
              <Button type="danger" size="small" disabled>
                删除
              </Button>
            )}
          </Space>
        ),
      },
    ];
    return (
      <Table
        className="table"
        columns={columns}
        dataSource={this.state.dataSource}
        rowKey={(record) => record.id}
      />
    );
  }
}
